<?php

namespace App\Models;

class Article extends Base
{
    protected $table = 'articles';

    const STATUS_1 = 1;
    const STATUS_2 = 2;

    const STATUS_TEXT = [
        self::STATUS_1 => '<span class="el-tag">正常</span>',
        self::STATUS_2 => '<span class="el-tag el-tag--danger">锁定</span>',
    ];

    protected $fillable = [
        'id','title','content','thumb','cid','describe','status',
        'created_at','updated_at',
    ];
    public function category(){
        return $this->belongsTo('App\Models\Category', 'cid', 'id');
    }


    /**
     * 获取列表
     * @param array $params 条件参数
     * @param array $fields 查询的字段
     * @return mixed
     */
    protected function getList($params = [], $fields = ['*']){
        $lists = $this->select($fields)
            ->where(function ($query) use ($params) {
                if(isset($params['kwd']) && $params['kwd']) {
                    $query ->where('title','like','%' . $params['kwd'] . '%');
                }
                if(isset($params['status']) && $params['status']) {
                    $query ->where('status',$params['status']);
                }
                if(isset($params['cid']) && $params['cid']) {
                    $query ->where('cid',$params['cid']);
                }
            })->with(['category' => function ($query) {
                $query->select(['id','name'])->get();
            }])->orderBy('id', 'desc')
            ->paginate(config('app.limit'));

        $this->stateToText($lists,[
            'status'=> self::STATUS_TEXT,
        ]);
        return $lists;
    }

    /**
     * 获取列表
     * @return mixed
     */
    protected function getWebList($cid){
        $lists = $this->select(['id','title','thumb','cid','created_at','describe'])
            ->where('cid',$cid)
            ->where('status',self::STATUS_1)
            ->orderBy('created_at', 'desc')
            ->paginate(5);
        return $lists;
    }


    /**
     * 获取列表
     * @return mixed
     */
    protected function getInfo($id){
        $info = self::with(['category' => function ($query) {
            $query->select(['id','name'])->get();
        }])->findOrFail($id);
        return $info;
    }
}
